/**
 * 通用uni-app网络请求
 * 基于 Promise 对象实现更简单的 request 使用方式，支持请求和响应拦截
 */

/*
// 开放的接口

*/
import utils from './utils';
import store from '@/store';
import {api_url, api_notoken, tenant_id} from './config';
let log = true;
if (process.env.NODE_ENV == 'production') {
	// 生产环境
	log = true;
}else{
	// 开发环境
	log = true;
}
function Client (method, action, params, callback, failback, opt , type) {
    let default_options = {
        url: api_url + action,
        header:{
            'TENANT-ID': tenant_id,
            Authorization: 'Basic cGlnOnBpZw=='
        },
        data: params,
        method: method.toUpperCase(),
    };
    let options = opt || {};
    let access_token= store.state.access_token;
    if (process.env.NODE_ENV === 'development') {
        access_token = uni.getStorageSync('access_token');
    }
    if(api_notoken.indexOf(action) == -1){
        if(access_token){
            default_options.header.Authorization = 'Bearer ' + access_token;
        }
    }    
    // 请求
    if(type != 'noLoading'){
        uni.showLoading();
    }    
    return new Promise((resolve, reject) => {
        let complete = {
            complete: (res) => {
                // if(log) console.log('[API]',res.config.method,res.config.url)
			    if(log) console.log(default_options.method + '响应：' + default_options.url,res)

                if(type != 'noLoading'){
                    uni.hideLoading();
                }                
                if(res.statusCode == 200){ // 请求成功
                    if(type == 'all'){
                        resolve(res.data);
                        if(typeof(callback) === 'function'){
                            callback(res.data);
                        }
                        return;
                    }
                    if(res.errMsg == 'request:fail ' || res.data.status == 503){
                        if (typeof (failback) === 'function') {
                            failback(res);
                        }
                        return false;
                    }
                    let {code,data,msg} = res.data;
                    if (code == 0 || code == 200) {
                        resolve(data);
                        if(typeof(callback) === 'function'){
                            callback(data, msg);
                        }
                    } else {
                        if(data == access_token && msg == access_token && !store.state.show_msgBox){ // 有种情况是请求成功，但返回当前token，说明token已过期
                            store.commit('setShowMsgBox', true);
                            utils.gotoLogin('登录过期，请重新登');
                        }
                        uni.showToast({title: msg, icon: 'none'});
                        if(type == 'all'){
                            reject(res.data);
                            if (typeof (failback) === 'function') {
                                failback(res.data);
                            }
                        }else{
                            reject(data);
                            if (typeof (failback) === 'function') {
                                failback(msg);
                            }
                        }
                    }
                }else if(res.statusCode == 401){
                    if((res.data.msg == '没有登录' || res.data.msg == 'jwt expired') && !store.state.show_msgBox){
                        store.commit('setShowMsgBox', true);
                        utils.gotoLogin('登录过期，请重新登录');
                    }
                    if(res.data.data == '用户不存在'){
                        // reject(res.data);
                        if (typeof (failback) === 'function') {
                            failback(res.data.data);
                        }
                    }
                }else{ // 请求失败
                    uni.showToast({title: res.data.msg, icon: 'none'});
                    reject(res.data);
                    if (typeof (failback) === 'function') {
                        failback(res.statusCode);
                    }
                }
            }            
        };
        let new_options = Object.assign({}, default_options, complete, options);
        // if(log) console.log('[API]',new_options.method,new_options.url)
		if(log) console.log(new_options.method + '请求：' + new_options.url,new_options)
        uni.request(new_options);
    })
}

export default Client;
